﻿/* jQuery Extensions */
jQuery.fn.outerHTML = function(s) {
    return (s)
? this.before(s).remove()
: jQuery("<p>").append(this.eq(0).clone()).html();
}

/* extension for centering */
jQuery.fn.center = function () {
    this.css("position", "absolute");
    this.css("top", ($(window).height() - this.height()) / 2 + $(window).scrollTop() + "px");
    this.css("left", ($(window).width() - this.width()) / 2 + $(window).scrollLeft() + "px");
    return this;
}

function htmlEncode(value) {
    return $('<div/>').text(value).html();
}

function htmlDecode(value) {
    return $('<div/>').html(value).text();
} 

/*---------------------------------------------------------------------------- 
    Contains global definitions
---------------------------------------------------------------------------- */
///
/// Global entry point. Put all init code here.
///
function globalLoad() {
    // server name is now injected into the Site.master page straight from the configuraton database and initialized in globalLoad()
    serverName = $("#txtServiceUrl").val();
    membershipPasswordRetrieveUrl = serverName + membershipPasswordRetrieveUrl;
    newsSourceUrl = serverName + newsSourceUrl;
    newsHeadlineUrl = serverName + newsHeadlineUrl;
    newsSearchUrl = serverName + newsSearchUrl;
    hitUpdateUrl = serverName + hitUpdateUrl;
    newsSectionUrl = serverName + newsSectionUrl;
    accountsLoadUrl = serverName + accountsLoadUrl;
    accountsGetUserUrl = serverName + accountsGetUserUrl;
    accountsSaveUserUrl = serverName + accountsSaveUserUrl;
    accountsSavePresetAvatarUrl = serverName + accountsSavePresetAvatarUrl;
    preSetImagesUrl = serverName + preSetImagesUrl;
    avatarUrl = serverName + avatarUrl;
    fileUploadUrl = serverName + fileUploadUrl;
    avatarImageUrl = serverName + avatarImageUrl;
    lookupCountriesUrl = serverName + lookupCountriesUrl;
    lookupStatesUrl = serverName + lookupStatesUrl;
    lookupUsersUrl = serverName + lookupUsersUrl;
    transactionsLoadUrl = serverName + transactionsLoadUrl;
    widgetGetPagesUrl = serverName + widgetGetPagesUrl;
    widgetGetWidgetUrl = serverName + widgetGetWidgetUrl;
    widgetCreatePageUrl = serverName + widgetCreatePageUrl;
    widgetDeletePageUrl = serverName + widgetDeletePageUrl;
    widgetEditPageUrl = serverName + widgetEditPageUrl;
    widgetAllUrl = serverName + widgetAllUrl;
    accountRegisterUserUrl = serverName + accountRegisterUserUrl;
    adminRolesGetUrl = serverName + adminRolesGetUrl;
    adminRolesSaveUrl = serverName + adminRolesSaveUrl;
    adminRolesDeleteUrl = serverName + adminRolesDeleteUrl;

    adminUserGetUsers = serverName + adminUserGetUsers;
    adminUserGetUsersWithRoles = serverName + adminUserGetUsersWithRoles;
    adminUserDeleteUser = serverName + adminUserDeleteUser;
    adminUserAddUserToRole = serverName + adminUserAddUserToRole;
    adminUserDeleteUserFromRole = serverName + adminUserDeleteUserFromRole;

    /* Automatically add progress to ajax calls */
    $('#loadingDiv')
                .hide()  // hide it initially 
                .ajaxStart(function () {
                    $(this).show();
                })
                .css('z-index', 9999) /* The progress should appear on top of everything else */
                .ajaxStop(function () {
                    $(this).hide();
                });
    if ($("#picProfile") != null) {
        $("#picProfile").attr("src", GetPicProfileUrl("50", "50"));
    }
    $("#errorMore").hide();
    $("#errorMore").accordion({ collapsible: true, autoHeight: false
    });    
}

function GetPicProfileUrl(height, width) {
    return avatarUrl + "?userid=" + $("#txtUserId").val() + "&Height=" + height + "&Width=" + width;
}

///
/// Calls a web service using JSONP
///
function CallWebService(url, input, callBack) {
    url = url + "?callback=?";
    $.getJSON(url, input, callBack);
}

// generic error display function
function ShowErrorMessage(response) {
    if (bShowServiceErrors == true) {
        $("#errorSummary").text(response.FriendlyErrorMessage);
        $("#errorDetail").text(response.ErrorMessage);
        $("#error").dialog({
            bgiframe: true,
            height: 'auto',
            width: 700,
            modal: true,
            title: "Error",
            close: function() { $(this).dialog("destroy"); }
        });
        $("#errorMore").show();        
    }
    else {
        $("#errorSummary").html(sGenericErrorMessage);
        $("#errorMore").hide();     
        $("#error").dialog({
            bgiframe: true,
            height: 'auto',
            width: 700,
            modal: true,
            title: "Error",
            close: function () { $(this).dialog("destroy"); }
        });
        $("#errorMore").hide();
    }
}

function ShowErrorDetails(ctrl) {
    if (ctrl.state == "min") {
        ctrl.state = "max";
        $("#errorDetail").show();
    } else {
        ctrl.state = "min";
        $("#errorDetail").hide();
    }    
}

function removeSpaces(string) {l
    return string.split(' ').join('');
}

function ConvertToJSONDate(dte) {
    var okDate = /Date\(([-+]?\d+[-+]?\d+)\)/.exec(dte)
    var when = null;
    if (okDate) {
        var when = new Date(eval(okDate[1]));
    }
    return when;

}


// Writes messages on the information panel.
// To use this simply drop a <div id="statusBar"/> into your page
// Severity = "Information", "Warning", "Error"
function WriteMessage(title, message, severity) {
    $("#statusBar").html("<div class='statusBox'><div class='statusHeader'>" + title + "<div class='windowControls'>" +
        "<img src='/images/popout.png' alt='close' style='height:15px; width:15px; top:10px;' onclick='InformationBarPopout();'\>" +
        "<img src='/images/close.png' alt='close' style='height:15px; width:15px; top:10px;'\>" +
        "</div></div>" + 
        "<div class=statusDetail'>" +
        message + "</div></div>");
}

function InformationBarPopout() {
    $('#statusBar').dialog({
        autoOpen: false,
        width: 400,
        height: 360,
        resizable: true,
        buttons: { "Ok": function() { $(this).dialog("destroy"); } }
    });
    $('#statusBar').dialog('open');
}

// execute a function dynamically
// executeFunctionByName("My.Namespace.functionName", window, arguments); 
// executeFunctionByName("Namespace.functionName", My, arguments); 
function executeFunctionByName(functionName, context /*, args */) {
    var args = Array.prototype.slice.call(arguments).splice(2);
    var namespaces = functionName.split(".");
    var func = namespaces.pop();
    for (var i = 0; i < namespaces.length; i++) {
        context = context[namespaces[i]];
    }
    return context[func].apply(this, args);
} 
